package com.ruicar.afs.cloud.channel.grade.ao;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.admin.api.feign.AfsUserFeign;
import com.ruicar.afs.cloud.channel.grade.constant.Constants;
import com.ruicar.afs.cloud.channel.grade.entity.*;
import com.ruicar.afs.cloud.channel.grade.service.*;
import com.ruicar.afs.cloud.channel.grade.service.impl.GradeModelCalcService;
import com.ruicar.afs.cloud.channel.grade.vo.GradeDataETVO;
import com.ruicar.afs.cloud.channel.grade.vo.GradeModelSubDataElementVO;
import com.ruicar.afs.cloud.channel.grade.vo.GradeResultReturnVO;
import com.ruicar.afs.cloud.channel.grade.vo.GradeResultVO;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.entity.ChannelRiskInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.online.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.job.core.util.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @version 1.0
 * @description: 介于service和controller层之间的ao层
 * @projectName：afs-backend
 * @className：GradeModelAO
 * @see: com.ruicar.afs.cloud.channel.grade.ao
 * @author： jiangxiongfei
 * @createTime：2020-08-14 21:47
 */
@Slf4j
@AllArgsConstructor
@Component
public class GradeModelAO {
    private static final Logger logger = LoggerFactory.getLogger(GradeModelAO.class);

    @Autowired
    private GradeModelInfoService gradeModelInfoService;
    @Autowired
    private GradeModelResultService gradeModelResultService;
    @Autowired
    private GradeModelElementService gradeModelElementService;
    @Autowired
    private GradeModelElementListService gradeModelElementListService;
    @Autowired
    private GradeModelResultDtlService gradeModelResultDtlService;
    @Autowired
    private GradeModelResultSubDtlService gradeModelResultSubDtlService;
    @Autowired
    private GradeModelSubDataelementService gradeModelSubDataelementService;
    @Autowired
    private GradeScoreRelaService gradeScoreRelaService;
    @Autowired
    private ChannelOnlineService channelOnlineService;
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;

    private AfsUserFeign afsUserFeign;


    /***************************************************************************
     * 计算各类模型结果并保存 处理方法，供不同具体业务模型调用的方法 -- for 授信管理 > 授信申请 > 授信方案建立 债项评级 第一屏
     * -- for 授信管理 > 授信申请 > 授信方案建立 利率定价 第一屏
     * @param brcode
     *            机构编号
     * @param trlno
     *            操作员编号
     * @param gradeInfoMap
     *            模型指标关系实体
     *            (如：gradeDataETBean.setCode(gradeno);gradeDataETBean.setKey(gradeFieldName);
     *            gradeDataETBean.setValue(value); gradeInfoMap.put(gradeno,
     *            gradeDataETBean);)
     *
     * @param modelCode
     *            模型代码
     * @param flag
     *            操作标志：查询 或 是评分，可通过这个标志判断是否要评分记录数据
     *            0-评分 1-查询
     * @param gradeResultReturnVO
     *            模型结果bean对象
     * @param mapSubDataElementbean
     *            存放指标公式数据项Map对象
     * @param opFlag
     *            用来判断只是保留模型指标具体值并不评分，还是既保留模型指标分又评分操作；0 - 保留模型指标业务具体值，不进行评分操作；1 -
     *            同时保留模型指标业务值和评分
     * @return
     * @throws Exception
     */
    public GradeResultReturnVO handleModelRecordResult(Long brcode, Long trlno, Map gradeInfoMap, String modelCode, String flag, GradeResultReturnVO gradeResultReturnVO,
                                                       Map<String, GradeModelSubDataElementVO> mapSubDataElementbean, String opFlag, GradeBigDataQuota quota) throws Exception {

        try {
            // 如果为查看则不记录数据
            if (StringUtils.isBlank(flag) || "0".equals(flag)) { // 进行评分，记录数据

                // 第一步：检查模型是否正确配置
                //checkModelIsValidByWeight(modeCode);

                // 第二步：获取评分模型
                //GradeModelInfo gradeModelInfo = getGradeModelInfo(brcode, modeCode);
                GradeModelInfo gradeModelInfo = null;
                List<GradeModelInfo> list = gradeModelInfoService.list(Wrappers.<GradeModelInfo>query().lambda().eq(GradeModelInfo::getModelCode, modelCode));
                if (CollectionUtils.isNotEmpty(list)) {
                    gradeModelInfo = list.get(0);
                }

                // 第三步： 获取模型指标,获取到指标号、指标当前值、指标分(未考虑权重或其它特殊要求的分数)、指标状态
                this.getGradeInfo(gradeResultReturnVO, gradeModelInfo.getModelCode(), gradeInfoMap, opFlag);

                gradeResultReturnVO.setGradeInfoMap(gradeInfoMap);
                gradeResultReturnVO.setMapSubDataElement(mapSubDataElementbean);// 设置指标公式数据项对应Map,此Map可能不存在的情况，因为指标中涉及公式有录入项才会有值
                // 第四步：如下操作
                /** **同时保留模型指标业务值和评分操作***才需要执行下面条件中的方法**begin: */
                if (Constants.IS_YES_SAVAVALUE_EXAM.equals(opFlag)) {
                    // 计算各指标得分
                    /** 计算指标最后得分(可能需要考虑到权重及其它特殊要求)** */
                    this.getGradeScore(gradeResultReturnVO, false);
                }
                /** **同时保留模型指标业务值和评分**操作*end */

                // 第五步：如下操作 记录结果
                // 记录评分结果表，并保存一级指标分数汇总表
                GradeModelResult gradeModelResult = this.recordGradeModelResult(brcode, trlno, modelCode, gradeResultReturnVO, quota);
                // 记录评分明细表
                this.recordGradeModelResultDtl(brcode, trlno, gradeModelResult.getId(), gradeResultReturnVO);
                gradeResultReturnVO.setResultId(gradeModelResult.getId());

                /*
                 * 获取该指标的权重 author:yangyong start data:20101130
                 */
                /** 查询结果指标明细表信息 ************* begin: */
                List<GradeModelResultDtl> gradeModelResultDtlList = gradeModelResultDtlService.list(Wrappers.<GradeModelResultDtl>query().lambda().eq(GradeModelResultDtl::getGrantModelRstId,
                        gradeModelResult.getId()));
                if (CollectionUtils.isNotEmpty(gradeModelResultDtlList)) {
                    for (GradeModelResultDtl gradeModelResultDtl : gradeModelResultDtlList) {
                        List<GradeModelElement> gradeModelElementList = gradeModelElementService.list(Wrappers.<GradeModelElement>query().lambda()
                                .eq(GradeModelElement::getModelCode, modelCode)
                                .eq(GradeModelElement::getElementNo, gradeModelResultDtl.getGradeNo().toString()));
                        GradeModelElement gradeModelElement = null;
                        if (CollectionUtils.isNotEmpty(gradeModelElementList)) {
                            gradeModelElement = gradeModelElementList.get(0);
                        }

                        GradeResultVO gradeResultVO = new GradeResultVO();
                        gradeResultVO.setState(GradeResultVO.STATE_0);// 设置状态已评分
                        gradeResultVO.setScore(String.valueOf(gradeModelResultDtl.getDtlValue()));
                        gradeResultVO.setModelScore(String.valueOf(gradeModelResultDtl.getDtlValue()));
                        gradeResultVO.setModelsg(String.valueOf(gradeModelElement.getElementWeight()));
                        gradeResultVO.setValue(gradeModelResultDtl.getDtlStr());
                        gradeResultReturnVO.getGradeResultMap().put(gradeModelElement.getElementNo(), gradeResultVO);// 设置指标结果至Map中
                    }
                }
            } else {// 只查看不记录数据
                GradeModelResult gradeModelResult = gradeModelResultService.getOne(Wrappers.<GradeModelResult>query().lambda().eq(GradeModelResult::getId, gradeResultReturnVO.getResultId()));

                gradeResultReturnVO.setResultId(gradeModelResult.getId());
                gradeResultReturnVO.setGrade(gradeModelResult.getModelValue());
                gradeResultReturnVO.setScore(gradeModelResult.getModelSocre());
                gradeResultReturnVO.setRemark(gradeModelResult.getRemark());
                /** 查询结果指标明细表信息 ************* begin: */
                List gradeModelResultDtlList = gradeModelResultDtlService.list(Wrappers.<GradeModelResultDtl>query().lambda().eq(GradeModelResultDtl::getGrantModelRstId, gradeModelResult.getId()));
                Iterator iter = gradeModelResultDtlList.iterator();
                while (iter.hasNext()) {
                    GradeModelResultDtl gradeModelResultDtl = (GradeModelResultDtl) iter.next();

                    List<GradeModelElement> gradeModelElementList = gradeModelElementService.list(Wrappers.<GradeModelElement>query().lambda().eq(GradeModelElement::getModelCode,
                            gradeModelResult.getModelCode()).eq(GradeModelElement::getElementNo, gradeModelResultDtl.getGradeNo().toString()));
                    GradeModelElement gradeModelElement = gradeModelElementList.get(0);

                    GradeResultVO gradeResultVO = new GradeResultVO();
                    gradeResultVO.setState(GradeResultVO.STATE_0);// 设置状态已评分
                    gradeResultVO.setScore(String.valueOf(gradeModelResultDtl.getDtlValue()));
                    gradeResultVO.setModelScore(String.valueOf(gradeModelResultDtl.getDtlValue()));
                    gradeResultVO.setModelsg(String.valueOf(gradeModelElement.getElementWeight()));
                    gradeResultVO.setValue(gradeModelResultDtl.getDtlStr());
                    gradeResultReturnVO.getGradeResultMap().put(gradeModelElement.getElementNo(), gradeResultVO);// 设置指标结果至Map中
                }
                /** 查询结果指标明细表信息 ************* end */
            }
            return gradeResultReturnVO;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("评级计算异常");
        }
    }

    private void getGradeInfo(GradeResultReturnVO gradeResultReturnVO, String modelCode, Map gradeInfoMap, String opFlag) throws Exception {
        try {
            GradeModelInfo gradeModelInfo = null;
            List<GradeModelInfo> list = gradeModelInfoService.list(Wrappers.<GradeModelInfo>query().lambda().eq(GradeModelInfo::getModelCode, modelCode));
            if (CollectionUtils.isNotEmpty(list)) {
                gradeModelInfo = list.get(0);
            }

            if (gradeModelInfo == null) {
                logger.error("没有找到指定的评分模型信息[" + modelCode + "-" + gradeModelInfo.getModelName() + "]");
                throw new Exception("没有找到指定的评分模型信息[" + modelCode + "-" + gradeModelInfo.getModelName() + "]");
            }
            gradeResultReturnVO.setGradeModelInfo(gradeModelInfo);

            List<GradeModelElement> elementList = gradeModelElementService.list(Wrappers.<GradeModelElement>query().lambda().eq(GradeModelElement::getModelCode,
                    modelCode).eq(GradeModelElement::getElementType, Constants.GRADE_MODEL_ELEMENT_TYPE_2));

            // get gradeModelElementMap
            Map gradeModelElementMap = new HashMap();
            if (CollectionUtils.isNotEmpty(elementList)) {
                for (GradeModelElement gradeModelElement : elementList) {
                    gradeModelElementMap.put(gradeModelElement.getElementNo(), gradeModelElement);// 将查询到的模型与指标关系记录以指标编号为KEY存入MAP中
                }
            }

            // loop gradeInfoMap
            Iterator gradeInfoMapKeyIt = gradeInfoMap.keySet().iterator();
            String gradeNo = null;
            while (gradeInfoMapKeyIt.hasNext()) {
                gradeNo = (String) gradeInfoMapKeyIt.next();

                /* 如果该指标没有配置,则不参与评分,跳出 */
                if (!gradeModelElementMap.containsKey(gradeNo)) {// 若指标未与该模型建立关系，则跳过
                    continue;
                }

                GradeModelElement gradeModelElement = (GradeModelElement) gradeModelElementMap.get(gradeNo);
                gradeResultReturnVO.setModelCode(modelCode);
                /** ******只保留模型指标业务具体值并不评分***相应处理*****begin:***** */
                if (Constants.IS_SAVAVALUE_NO_EXAM.equals(opFlag)) {
                    // 0 - 保留模型指标业务具体值并不评分
                    if (!gradeModelElementMap.containsKey(gradeNo)) {// 若指标未与该模型建立关系，则提示
                        logger.error("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + modelCode + "-" + gradeModelInfo.getModelName() + "]中未定义");
                        throw new Exception("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + modelCode + "-" + gradeModelInfo.getModelName() + "]中未定义");
                    }

                    GradeDataETVO gradeDataETVO = (GradeDataETVO) gradeInfoMap.get(gradeNo);
                    GradeResultVO gradeResultVO = new GradeResultVO();
                    gradeResultVO.setGradeNo(gradeNo);
                    gradeResultVO.setValue(gradeDataETVO.getValue());
                    gradeResultVO.setGradeName(gradeModelElement.getElementName());// 指标要素名称
                    gradeResultVO.setUpElementNo(gradeModelElement.getUpElementNo());//上一级指标，用于一级指标汇总分数 add by jiangxiongfei 20200824
                    gradeResultReturnVO.getGradeResultMap().put(gradeDataETVO.getKey(), gradeResultVO);// Key 为指标元素表中配制的字段名
                    /** ******保留模型指标业务具体值并不评分***相应处理*****end***** */
                } else {
                    /** ******1 - 同时保留模型指标业务值和评分***相应处理*****begin:***** */
                    this.getGradeSingleElementResult(gradeResultReturnVO, gradeInfoMap, gradeModelElementMap, gradeNo);
                    /** ******1 - 同时保留模型指标业务值和评分***相应处理*****end***** */
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 获取不同模型自身指标得分，该得分考虑到指标权重、得分上下限等因素的处理结果
     *
     * @param gradeResultReturnVO 模型结果Bean
     * @return
     * @throws Exception
     */
    private void getGradeScore(GradeResultReturnVO gradeResultReturnVO, boolean singleFlg) throws Exception {
        try {
            Map gradeResultMap = gradeResultReturnVO.getGradeResultMap();
            Map gradeMap = new HashMap();
            DecimalFormat format = new DecimalFormat();
            format.setGroupingSize(0);
            // grade score
            BigDecimal score = new BigDecimal(0);
            Iterator gradeResultMapKeyIt = gradeResultMap.keySet().iterator();
            String gradeFieldName = null;
            GradeResultVO gradeResultVO = null;
            while (gradeResultMapKeyIt.hasNext()) {
                gradeFieldName = (String) gradeResultMapKeyIt.next();
                gradeResultVO = (GradeResultVO) gradeResultMap.get(gradeFieldName);

                /** 只处理已评分或无法评分，不可忽略状态下的分数* */
                if (GradeResultVO.STATE_0.equals(gradeResultVO.getState()) // 0-已评分
                        || GradeResultVO.STATE_5.equals(gradeResultVO.getState())) { // 5-无法评分,不可忽略
                    gradeMap.put(gradeFieldName, gradeResultVO);
                }
            }
            Iterator gradeMapKeyIt = gradeMap.keySet().iterator();

            // 要素分值 最初分值
            BigDecimal eleScore = new BigDecimal(0);
            // 模型指标中要素得分 通过处理指标权重或其它因素 计算出的最后得分
            BigDecimal postScore = new BigDecimal(0);
            // 模型指标要素权重
            BigDecimal preSq = new BigDecimal(0);

            //一级指标汇总分数map，key：一级指标编码，value：级指标汇总分数  add by jiangxiongfei 20200824
            Map<String, BigDecimal> level1ElementSumScoreMap = new HashMap<String, BigDecimal>();

            while (gradeMapKeyIt.hasNext()) {
                gradeFieldName = (String) gradeMapKeyIt.next();
                gradeResultVO = (GradeResultVO) gradeMap.get(gradeFieldName);
                try {
                    eleScore = new BigDecimal(gradeResultVO.getScore());
                } catch (RuntimeException e) {
                    logger.error(e.getMessage(), e);
                    logger.error("评分计算失败，模型" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "中["
                            + gradeResultVO.getGradeNo() + "-" + gradeResultVO.getGradeName() + "指标得分公式配置有误");
                    throw new Exception("评分计算失败，模型" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "中["
                            + gradeResultVO.getGradeNo() + "-" + gradeResultVO.getGradeName() + "指标得分公式配置有误");
                }
                postScore = eleScore;
                /** 乘以权重相应处理***begin:** */
                if (null != gradeResultVO.getSg() && !"".equals(gradeResultVO.getSg())) {
                    preSq = new BigDecimal(gradeResultVO.getSg());
                    postScore = preSq.multiply(eleScore);

                }
                /** 乘以权重相应处理***end** */

                /** 根据指标得分上下限是否存在 算出得分结果***begin:** */
                if (!"".equals(gradeResultVO.getHighScoreLimit())) {// 指标得分上限
                    if (postScore.compareTo(new BigDecimal(gradeResultVO.getHighScoreLimit())) == 1) {// 若计算得分比指标得分下限还大，则取指标上限值
                        postScore = new BigDecimal(gradeResultVO.getHighScoreLimit());// 指标的最后得分
                    }

                }

                if (!"".equals(gradeResultVO.getLowScoreLimit())) {// 指标得分下限
                    if (postScore.compareTo(new BigDecimal(gradeResultVO.getLowScoreLimit())) == -1) {// 若计算得分比指标得分下限还小，则取指标下限值
                        postScore = new BigDecimal(gradeResultVO.getLowScoreLimit());// 指标的最后得分
                    }
                }
                gradeResultVO.setModelScore(String.valueOf(postScore));// 设置模型指标最后得分
                gradeResultVO.setModelsg(String.valueOf(preSq));// //设置模型指标权重

                gradeResultVO.setScore(String.valueOf(postScore));// 设置模型指标最后得分，该值需要存在结果明细表中的
                gradeResultReturnVO.getGradeResultMap().put(gradeFieldName, gradeResultVO);// 重新对最后指标结果对进设置

                /** 根据指标得分上下限是否存在 算出得分结果*******end**** */
                // 计算出评分卡中的权重和频分
                // 个人存在权重
                /***************************************************************
                 * 原来代码 2010-10-22 所注
                 * if(modelCode.equals(GradeModelRela.MODEL_TYPE_0)){ postSq =
                 * preSq + (preSq * ignoreSg) / (100 - ignoreSg); postScore =
                 * (eleScore / 10) * (postSq / 100) * 100;
                 * gradeResultBean.setModelScore(String.valueOf(postScore));
                 * gradeResultBean.setModelsg(String.valueOf(postSq)); }else{
                 * postScore = eleScore;
                 * gradeResultBean.setModelScore(String.valueOf(postScore)); }
                 **************************************************************/
                if (singleFlg || !Constants.FLAG_ON.equals(gradeResultVO.getIsIgnore())) {// 若该指标忽略，则不累加到总分中
                    score = score.add(postScore);
                }
                //按一级指标分类汇总 add by jiangxiongfei 20200824 begin
                if (level1ElementSumScoreMap.containsKey(gradeResultVO.getUpElementNo())) {
                    BigDecimal scoretemp = level1ElementSumScoreMap.get(gradeResultVO.getUpElementNo()).add(postScore);
                    level1ElementSumScoreMap.put(gradeResultVO.getUpElementNo(), scoretemp);
                } else {
                    level1ElementSumScoreMap.put(gradeResultVO.getUpElementNo(), postScore);
                }
                //按一级指标分类汇总 add by jiangxiongfei 20200824 end
            }
            // 总得分
            gradeResultReturnVO.setScore(score);
            gradeResultReturnVO.setLevel1ElementSumScoreMap(level1ElementSumScoreMap);

        } catch (NumberFormatException e) {
            logger.error("评分计算失败，可能模型指标分值配置有误");
            logger.error(e.getMessage(), e);
            throw new Exception("评分计算失败，可能模型指标分值配置有误");
        } catch (Exception e) {
            logger.error("评分计算失败");
            logger.error(e.getMessage(), e);
            throw new Exception("评分计算失败");
        }
    }

    /***************************************************************************
     * 处理模型结果并保存
     *
     * @date 2010-10-21
     * @param brcode
     *            机构编号
     * @param tlrNo  操作员编号
     * @param modelCode
     *            模型编号
     * @param gradeResultReturnVO
     *            模型结果Bean
     */
    private GradeModelResult recordGradeModelResult(Long brcode, Long tlrNo, String modelCode, GradeResultReturnVO gradeResultReturnVO, GradeBigDataQuota quota) throws Exception {
        try {
            boolean opflag = false;// 用来判断是新增记录，还是更新记录 opflag = false
            // 表示新增记录；反之，则更新操作
            GradeModelResult gradeModelResult = null;
            // 通过ID判断记录是否存在，存在则更新记录，否则新增记录
            if (gradeResultReturnVO.getId() != null) {
                gradeModelResult = gradeModelResultService.getOne(Wrappers.<GradeModelResult>query().lambda().eq(GradeModelResult::getId, gradeResultReturnVO.getId()));
                opflag = true;
            }

            if (gradeModelResult == null) {
                gradeModelResult = new GradeModelResult();
                opflag = false;
            }
            gradeModelResult.setBrcode(brcode);// 所属机构代码
            gradeModelResult.setTlrno(tlrNo);// 评分人
            gradeModelResult.setModelType(gradeResultReturnVO.getModelType());// 模型类型
            gradeModelResult.setModelCode(modelCode);// 模型代码

            if (gradeResultReturnVO.getScore() != null && !"".equals(gradeResultReturnVO.getScore())) {
                gradeModelResult.setModelSocre(gradeResultReturnVO.getScore());// 模型得分
//				gradeModelResult.setModelChgSocre(new BigDecimal(gradeResultReturnBean.getScore()));// 默认系统评级分数为人工评级分数
            }
            gradeModelResult.setModelValue(gradeResultReturnVO.getGrade());// 级别
            gradeModelResult.setCustcd(gradeResultReturnVO.getCustcd());// 客户号
            /**modify by bingliang.li 20121116 bugid 4042 评级日期和期数会变化 begin*/
            gradeModelResult.setGradeDate(new Date()); // 评分日期
            gradeModelResult.setGradeValidDate(gradeResultReturnVO.getGradeValidDate()); // 评分有效期
            /**modify by bingliang.li 20121116 bugid 4042 评级日期和期数会变化 end*/
            gradeModelResult.setValidFlag(Constants.VALID_FLAG_UNVALID_0);// 有效标志
            gradeModelResult.setAppstat(Constants.APPSTAT_INPUTED);
            gradeModelResult.setLastUpdDate(new Date());// 最后修改日期
            gradeModelResult.setLastUpdTlr(tlrNo);// 最后修改操作员
            gradeModelResult.setTermType(gradeResultReturnVO.getTermType());// 期数类型
            /**modify by bingliang.li 20121116 bugid 4042 评级日期和期数会变化 begin*/
            gradeModelResult.setTerm(gradeResultReturnVO.getTerm());// 期数
            /**modify by bingliang.li 20121116 bugid 4042 评级日期和期数会变化 end*/
            gradeModelResult.setTimestamps(new Timestamp(System.currentTimeMillis()));// 时间戳
            //申请编号绑定
            gradeModelResult.setAppno(gradeResultReturnVO.getAppno());// 申请编号

            //长城新增字段 add by jiangxiongfei 20200816 begin
            gradeModelResult.setGradeType(Constants.GRADE_TYPE_MODEL_CALC); //试算类型
            if (quota != null) {
                gradeModelResult.setGradeType(Constants.GRADE_TYPE_BIGDATA); //大数据类型
                gradeModelResult.setChannelBelong(quota.getChannelBelong()); //渠道归属,只区分直营、非直营
                gradeModelResult.setBusinessType(quota.getBusinessType());
                gradeModelResult.setChannelCode(quota.getChannelCode());
                gradeModelResult.setChannelFullName(quota.getChannelFullName());
                //获取上一个月该渠道的新车业务类型的评级结果
                GradeModelResult resultTemp = gradeModelResultService.getOne(Wrappers.<GradeModelResult>query().lambda()
                        .eq(GradeModelResult::getChannelCode, quota.getChannelCode())
                        .eq(GradeModelResult::getBusinessType, quota.getBusinessType())  //业务类型：01-新车，02-二手车
                        .like(true, GradeModelResult::getGradeDateStr8, DateUtil.format(DateUtil.addMonths(new Date(), -1), "yyyyMM"))
                        .orderByDesc(GradeModelResult::getId));
                if (resultTemp != null) {
                    gradeModelResult.setLastModelValue(resultTemp.getModelValue());
                } else {
                    gradeModelResult.setLastModelValue("");
                }
                //获取客户经理名称
                gradeModelResult.setGradeDateStr8(DateFormatUtils.format(new Date(), "yyyyMMdd"));
                List<ChannelBaseInfoTemp> channelBaseInfoTempList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda()
                        .eq(ChannelBaseInfoTemp::getChannelCode, quota.getChannelCode()));
                if (CollectionUtils.isNotEmpty(channelBaseInfoTempList)) {
                    //详细渠道归属，区分直营、sp、总对总
                    gradeModelResult.setChannelBelongDtl(channelBaseInfoTempList.get(0).getChannelBelong());
                    List<ChannelRiskInfoTemp> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                            .eq(ChannelRiskInfoTemp::getChannelId, channelBaseInfoTempList.get(0).getId()));
                    if (CollectionUtils.isNotEmpty(channelRiskInfoTempList)) {
                        List<String> userNameList = new ArrayList<String>();
                        userNameList.add(channelRiskInfoTempList.get(0).getCustomerManager());
                        IResponse<List<UserSimpleInfoDto>> listIResponse = afsUserFeign.getSimpleInfoByUserLoginNames(userNameList);
                        if (listIResponse != null && CollectionUtils.isNotEmpty(listIResponse.getData())) {
                            gradeModelResult.setCustomerManager(listIResponse.getData().get(0).getUserRealName());
                        } else {
                            gradeModelResult.setCustomerManager("");
                        }
                    } else {
                        gradeModelResult.setCustomerManager("");
                    }
                } else {
                    gradeModelResult.setCustomerManager("");
                }
            }
            //长城新增字段 add by jiangxiongfei 20200816 end

            Map<String, BigDecimal> level1ElementSumScoreMap = gradeResultReturnVO.getLevel1ElementSumScoreMap();
            Map<String, Long> gradeModelResultSubDtlIdMap = gradeResultReturnVO.getGradeModelResultSubDtlIdMap();
            if (opflag) {
                //修改模型评分结果
                gradeModelResultService.updateById(gradeModelResult);

                //修改一级指标汇总结果。删除后再新增，防止未清除干净 add by jiangxiongfei 20200824 begin
                gradeModelResultSubDtlService.remove(Wrappers.<GradeModelResultSubDtl>query().lambda().eq(GradeModelResultSubDtl::getGrantModelRstId, gradeModelResult.getId()));

                if (CollectionUtils.isNotEmpty(level1ElementSumScoreMap)) {
                    for (Map.Entry<String, BigDecimal> entry : level1ElementSumScoreMap.entrySet()) {
                        GradeModelResultSubDtl gradeModelResultSubDtl = new GradeModelResultSubDtl();
                        gradeModelResultSubDtl.setGradeNo(entry.getKey());//gradeModelResultSubDtl的指标编号（二级指标的上级编号）
                        gradeModelResultSubDtl.setScore(entry.getValue());
                        gradeModelResultSubDtl.setGrantModelRstId(gradeModelResult.getId());
                        gradeModelResultSubDtlService.save(gradeModelResultSubDtl);

                        //缓存一级指标汇表id
                        gradeModelResultSubDtlIdMap.put(entry.getKey(), gradeModelResultSubDtl.getId());
                    }
                }
                //修改一级指标汇总结果。删除后再新增，防止未清除干净 add by jiangxiongfei 20200824 end
            } else {
                //修改模型评分结果
                gradeModelResultService.save(gradeModelResult);
                gradeResultReturnVO.setId(gradeModelResult.getId());

                //新增保存一级指标分数汇总 add by jiangxiongfei 20200824 begin
                if (CollectionUtils.isNotEmpty(level1ElementSumScoreMap)) {
                    for (Map.Entry<String, BigDecimal> entry : level1ElementSumScoreMap.entrySet()) {
                        GradeModelResultSubDtl gradeModelResultSubDtl = new GradeModelResultSubDtl();
                        gradeModelResultSubDtl.setGradeNo(entry.getKey());
                        gradeModelResultSubDtl.setScore(entry.getValue());
                        gradeModelResultSubDtl.setGrantModelRstId(gradeModelResult.getId());
                        gradeModelResultSubDtlService.save(gradeModelResultSubDtl);

                        //缓存一级指标汇表id
                        gradeModelResultSubDtlIdMap.put(entry.getKey(), gradeModelResultSubDtl.getId());
                    }
                }
                //新增保存一级指标分数汇总 add by jiangxiongfei 20200824 end
            }
            gradeResultReturnVO.setGradeModelResultSubDtlIdMap(gradeModelResultSubDtlIdMap);
            return gradeModelResult;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("评分结果记录失败");
        }
    }

    /***************************************************************************
     * 处理模型中各指标结果并保存
     *
     * @param brcode
     *            机构编号
     * @param trlno
     *            操作员编号
     * @param modelResultId
     *            对应模型结果表ID
     * @param gradeResultReturnVO
     *            模型结果 Bean
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @date 2010-10-21
     */
    private void recordGradeModelResultDtl(Long brcode, Long trlno, Long modelResultId, GradeResultReturnVO gradeResultReturnVO) throws Exception {
        Map gradeResultMap = gradeResultReturnVO.getGradeResultMap();
        Iterator gradeResultMapIt = gradeResultMap.keySet().iterator();

        // 根据模型结果ID，查询结果明细表记录，目的是:用来判断是结果明细表中是否更新操作，还是新增操作
        List<GradeModelResultDtl> gradeModelResultDtlList = gradeModelResultDtlService.list(Wrappers.<GradeModelResultDtl>query().lambda().eq(GradeModelResultDtl::getGrantModelRstId, modelResultId));
        //modify by jiangxiongfei
        // /*
        //  * add by kangbyron 20110119
        //  * 记录评分结果,总是每次先删除历史明细,再新增,避免出现由于不同模型的要素不一样而导致的残留数据没清掉的问题 begin
        //  */
        // if (CollectionUtils.isNotEmpty(gradeModelResultDtlList)) {
        //     for (int i = 0; i < gradeModelResultDtlList.size(); i++) {
        //         GradeModelResultDtl gradeModelResultDtl = gradeModelResultDtlList.get(i);
        //         gradeModelResultDtlService.removeById(gradeModelResultDtl.getId());
        //     }
        //     gradeModelResultDtlList = null; // 删除完成后把list置null
        // }
        /*
         * add by kangbyron 20110119
         * 记录评分结果,总是每次先删除历史明细,再新增,避免出现由于不同模型的要素不一样而导致的残留数据没清掉的问题 end
         */
        Map gradeModelResultDtlMap = new HashMap();
        while (gradeResultMapIt.hasNext()) {

            GradeModelResultDtl gradeModelResultDtl = new GradeModelResultDtl();
            String gradeFieldName = (String) gradeResultMapIt.next();
            GradeResultVO gradeResultVO = (GradeResultVO) gradeResultMap.get(gradeFieldName);

            boolean opFlag = true; // 控制判断结果明细表中是否存在相同指标记录，若查找到相同的指标记录，则退出循环，进行更新操作
            GradeModelResultDtl gradeModelResultDtlTemp = null;
            /** ***************判断结果明细表记录是否已存在****begin:******************* */
            if (gradeModelResultDtlList != null) {
                Iterator gradeNoIter = gradeModelResultDtlList.iterator();
                while (gradeNoIter.hasNext() && opFlag) {
                    gradeModelResultDtlTemp = (GradeModelResultDtl) gradeNoIter.next();
                    if (gradeModelResultDtlTemp.getGradeNo().equals(gradeResultVO.getGradeNo())) {
                        try {
                            org.apache.commons.beanutils.BeanUtils.copyProperties(gradeModelResultDtl, gradeModelResultDtlTemp);
                        } catch (IllegalAccessException e) {
                            log.error("GradeModelResultDtl指标明细结果存取错误" + e.getMessage());
                            throw new Exception("GradeModelResultDtl指标公式数据项存取错误");
                        } catch (InvocationTargetException e) {
                            log.error("GradeModelResultDtl指标明细结果存取错误" + e.getMessage());
                            throw new Exception("GradeModelResultDtl指标公式数据项存取错误");
                        }// 对象属性复制
                        opFlag = false;
                    }
                }
            }
            /** ***************判断结果明细表记录是否已存在***********end********** */
            gradeModelResultDtl.setGrantModelRstId(modelResultId);
            String gradeNo = "0";
            if (StringUtils.isNotBlank(gradeResultVO.getGradeNo())) {
                gradeNo = gradeResultVO.getGradeNo();
            }

            //gradeModelResultDtl增加字段SubId保存 add by jiangxiongfei 20200824 begin
            // 通过一级指标查subId，一级指标编号对应的GradeModelResultSubDtl记录id map key-一级指标elementNO（二级指标的上级指标编号） value-一级记录gradeModelResultSubDtl对象id
            Map<String, Long> gradeModelResultSubDtlIdMap = gradeResultReturnVO.getGradeModelResultSubDtlIdMap();
            Long subId = gradeModelResultSubDtlIdMap.get(gradeResultVO.getUpElementNo());
            if (CollectionUtils.isNotEmpty(gradeModelResultSubDtlIdMap) && subId != null) {
                gradeModelResultDtl.setSubId(subId);
            } else {
                gradeModelResultDtl.setSubId(0L);
            }
            //gradeModelResultDtl增加字段SubId保存 add by jiangxiongfei 20200824 end


            gradeModelResultDtl.setGradeNo(new BigDecimal(gradeNo));
            gradeModelResultDtl.setDtlStr(gradeResultVO.getValue());
            String score = "0";
            if (StringUtils.isNotBlank(gradeResultVO.getScore())) {
                score = gradeResultVO.getScore();
            }
            gradeModelResultDtl.setDtlValue(new BigDecimal(score));
            // gradeModelResultDtlDAO.getHibernateTemplate().evict(gradeModelResultDtlTemp);
            gradeModelResultDtlService.saveOrUpdate(gradeModelResultDtl);

            // gradeModelResultDtlDAO.getHibernateTemplate().flush();

            /** 保存指标公式数据项结果 **************** begin:* */
            Map<String, GradeModelSubDataElementVO> mapSubDataElementBean = gradeResultReturnVO.getMapSubDataElement();
            this.recordGradeModelSubDataelement(brcode, trlno, gradeModelResultDtl, mapSubDataElementBean);
            /** 保存指标公式数据项结果 ****************end* */

            /** *将指标结果明细信息**以Map形式存入结果Bean中**begin:** */

            gradeModelResultDtlMap.put(gradeModelResultDtl.getGradeNo(), gradeModelResultDtl);

            /** *将指标结果明细信息**以Map形式存入结果Bean中**end** */
        }
        gradeResultReturnVO.setGradeModelResultDtlMap(gradeModelResultDtlMap);
    }

    /**
     * 通过模型已配置的指标要素分值，获到模型下单个指标的分值， 若得分值由公式表示则需要解析公式计算得分值， 注：此时的得分并未考虑权重及其它要求
     * 得出的分值
     * -- for 授信管理 > 授信申请 > 授信方案建立 债项评级 第一屏
     *
     * @param gradeResultReturnVO  模型结果Bean
     * @param gradeInfoMap         页面或批量或其它途径传入的Map值
     *                             (如：gradeDataETBean.setCode(gradeno);gradeDataETBean.setKey(gradeFieldName);
     *                             gradeDataETBean.setValue(value); gradeInfoMap.put(gradeno,
     *                             gradeDataETBean); )
     * @param gradeModelElementMap 该模型下对应的绑定指标关系
     * @param gradeNo              指标编号
     */
    protected void getGradeSingleElementResult(GradeResultReturnVO gradeResultReturnVO, Map gradeInfoMap, Map gradeModelElementMap, String gradeNo) throws Exception {
        List qryList = new ArrayList();// 存放SQL语句中条件值
        GradeDataETVO gradeDataETVO = (GradeDataETVO) gradeInfoMap.get(gradeNo);
        GradeResultVO gradeResultVO = new GradeResultVO();
        gradeResultVO.setGradeNo(gradeNo);
        gradeResultVO.setValue(gradeDataETVO.getValue());

        // grade mode not contains gradeno
        GradeModelElement gradeModelElement = (GradeModelElement) gradeModelElementMap.get(gradeNo);
        gradeResultVO.setGradeName(gradeModelElement.getElementName());

        /** ******1 - 同时保留模型指标业务值和评分***相应处理*****begin:***** */
        if (!gradeModelElementMap.containsKey(gradeNo)) {// 指标不存在，则设置不参与评分
            logger.error("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId() + "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中未定义");
            throw new Exception("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId() + "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中未定义");
        } else {
            if (null != gradeModelElement.getElementMax()) {// 指标得分上限
                gradeResultVO.setHighScoreLimit(String.valueOf(gradeModelElement.getElementMax()));
            }

            if (null != gradeModelElement.getElementMin()) {// 指标得分下限
                gradeResultVO.setLowScoreLimit(String.valueOf(gradeModelElement.getElementMin()));
            }

            if (StringUtils.isEmpty(gradeDataETVO.getValue())
                    && !Constants.LIMIT_FLAG_2.equals(gradeModelElement.getElementEditType())) {// 当指标值为空并指标值类型不为数据字典和区间定值时，还需要判断该指标是否参与评分
                if (gradeModelElement.getElementIgnore().equals(Constants.FLAG_ON)) {// 判断该指标是否忽略评分
                    gradeResultVO.setState(GradeResultVO.STATE_3);// 不参与评分
                } else {// 当该指标设定参与评分，但是指标当前值
                    gradeResultVO.setScore("0");
                    gradeResultVO.setState(GradeResultVO.STATE_0);// 已评分
                }

            } else {// 指标值不为空时，对应以下的处理
                // List modelElementList = gradeModelElementListDAO.queryByCondition(hql);// 查询指标要素值表记录
                List<GradeModelElementList> gradeModelElementListList = gradeModelElementListService.list(Wrappers.<GradeModelElementList>query().lambda()
                        .eq(GradeModelElementList::getElementNo, gradeNo)
                        .eq(GradeModelElementList::getModelCode, gradeResultReturnVO.getGradeModelInfo().getModelCode()));

                /** ******对于得分值为公式型**有效***将指标公式中的代码进行替换成实际数字值*******begin:******* */
                /** ******指标当前值******* */
                Map paramMap = new HashMap();
                if (null != gradeDataETVO.getRealValue() && !"".equals(gradeDataETVO.getRealValue())) {
                    paramMap.put(Constants.MODEL_INDEX_CURRENT_VALUE, gradeDataETVO.getRealValue());
                } else if (null != gradeDataETVO.getValue() && !"".equals(gradeDataETVO.getValue())) {// 指标当前值不为空，则赋自身值
                    paramMap.put(Constants.MODEL_INDEX_CURRENT_VALUE, gradeDataETVO.getValue());
                } else { // 否则为空，则设置为0
                    paramMap.put(Constants.MODEL_INDEX_CURRENT_VALUE, "0"); // 指标当前值
                }

                /******指标权重值*********** */
                if (gradeModelElement.getElementWeight() != null) {
                    paramMap.put(Constants.MODEL_INDEX_WEIGHT_SCORE, gradeModelElement.getElementWeight()); // 指标计划值
                }

                /******指标计划值*********** */
                if (gradeModelElement.getElementPlan() != null) {
                    paramMap.put(Constants.MODEL_INDEX_PLAN_VALUE, gradeModelElement.getElementPlan()); // 指标计划值
                }

                /******指标得分标准*********** */
                if (gradeModelElement.getElementStand() != null) {
                    paramMap.put(Constants.MODEL_INDEX_STAND_SCORE, gradeModelElement.getElementStand()); // 指标得分标准
                }
                /** ******对于得分值为公式型**有效***将指标公式中的代码进行替换成实际数字值*******end******* */

                // 未配置等指标不计算 20200924
//                if (CollectionUtils.isEmpty(gradeModelElementListList)) {
//                    // 判断若未找到符合的指标要素分值记录，则提示
//                    logger.error("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId() +
//                            "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中要素分值未配置!");
//                    throw new Exception("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId() +
//                            "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中要素分值未配置!");
//                }

                //打分处理
                if (Constants.ELEMENT_EDIT_TYPE_DATADIC.equals(gradeModelElement.getElementEditType())) {
                    // 不存在上下限区间条件限制，通过数据字典定值的相应处理
                    List<GradeModelElementList> modelElementList = gradeModelElementListService.list(Wrappers.<GradeModelElementList>query().lambda()
                            .eq(GradeModelElementList::getElementNo, gradeNo)
                            .eq(GradeModelElementList::getElementValue, gradeDataETVO.getValue())
                            .eq(GradeModelElementList::getModelCode, gradeResultReturnVO.getGradeModelInfo().getModelCode()));

                    if (modelElementList == null || modelElementList.size() == 0) {
                        if (Constants.FLAG_ON.equals(gradeModelElement.getElementIgnore())) { // 若不存在指标要素值并且可忽略指标，则设置为"4-无法评分,可忽略"
                            gradeResultVO.setState(GradeResultVO.STATE_3);
                        } else { // 若不存在指标要素值并且不可忽略指标，则设置为"5-无法评分,不可忽略"
                            gradeResultVO.setScore("0");
                            gradeResultVO.setState(GradeResultVO.STATE_5);
                        }
                    } else {
                        GradeModelElementList gradeModelElementList = (GradeModelElementList) modelElementList.get(0);
                        // 分计算公式和定值处理
                        if (gradeModelElementList.getScoreType() != null && gradeModelElementList.getScoreType().equals(Constants.SCORE_TYPE_1)) { // 定值
                            gradeResultVO.setScore(String.valueOf(gradeModelElementList.getScore()));
                        } else { // 计算公式
                            // 解析公式别并计算结果
                            String formula = gradeModelElementList.getScore();
                            if (null != formula && !"".equals(formula)) {
                                formula = formula.trim();// 去除公式中空字符串
                                try {
                                    gradeResultVO.setScore(computeResultByFormula(analyzeFormulaProcess(formula, paramMap, gradeResultReturnVO, gradeInfoMap, gradeModelElementMap)));
                                } catch (RuntimeException e) {
                                    logger.error("评分计算失败，模型" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "中[" + gradeResultVO.getGradeNo()
                                            + "-" + gradeResultVO.getGradeName() + "]指标得分公式配置有误，请检查");
                                    throw new Exception("评分计算失败，模型" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "中[" + gradeResultVO.getGradeNo()
                                            + "-" + gradeResultVO.getGradeName() + "]指标得分公式配置有误，请检查");
                                }
                            } else {
                                logger.error("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId()
                                        + "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中要素分值公式配置有误");
                                throw new Exception("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]为在模型[" + gradeResultReturnVO.getGradeModelInfo().getId()
                                        + "-" + gradeResultReturnVO.getGradeModelInfo().getModelName() + "]中要素分值公式配置有误");
                            }
                        }
                        gradeResultVO.setState(GradeResultVO.STATE_0);
                    }
                } else if (Constants.ELEMENT_EDIT_TYPE_RANGE.equals(gradeModelElement.getElementEditType())) {
                    try {
                        new BigDecimal(gradeDataETVO.getValue());
                    } catch (Exception e) {
                        logger.error("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]对应的值[" + gradeDataETVO.getValue() + "]填写有误");
                        throw new Exception("指标[" + gradeNo + "-" + gradeModelElement.getElementName() + "]对应的值[" + gradeDataETVO.getValue() + "]填写有误");
                    }

                    // 存在上下限区间条件相应处理
                    if (gradeModelElementListList == null || gradeModelElementListList.size() == 0) {
                        if (Constants.FLAG_ON.equals(gradeModelElement.getElementIgnore())) {// 若不存在指标要素值并且可忽略指标，则设置为"4-无法评分,可忽略"
                            gradeResultVO.setState(GradeResultVO.STATE_3);
                        } else { // 若不存在指标要素值并且可忽略指标，则设置为"5-无法评分,不可忽略"
                            gradeResultVO.setScore("0");
                            gradeResultVO.setState(GradeResultVO.STATE_5);
                        }
                    } else {
                        /** *存在指标值 对应的处理** */
                        GradeModelElementList gradeModelElementList = null;

                        /** 以下循环该指标下的要素值，判断出合适的要素值记录 *****begin:* */
                        gradeModelElementList = this.getGradeModelElementListByLimit(gradeDataETVO, gradeModelElementListList);
                        if (gradeModelElementList == null) {
                            // 判断若未找到符合的指标要素分值记录，则提示
                            logger.error("指标[" + gradeNo + "-"
                                    + gradeModelElement.getElementName() + "]为在模型["
                                    + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                    + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                    + "]中要素分值配置有误，未找到符中指标当前值的要素分值信息");
                            throw new Exception("指标[" + gradeNo + "-"
                                    + gradeModelElement.getElementName() + "]为在模型["
                                    + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                    + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                    + "]中要素分值配置有误，未找到符中指标当前值的要素分值信息");
                        }
                        /** 以上循环该指标下的要素值，判断出合适的要素值记录 *****end**** */

                        // 分计算公式和定值处理
                        if (Constants.SCORE_TYPE_1.equals(gradeModelElementList.getScoreType())) { // 数值定值 即 非公式表示型
                            gradeResultVO.setScore(String.valueOf(gradeModelElementList.getScore()));
                        } else { // 计算公式
                            // 解析公式并计算结果
                            String formula = gradeModelElementList.getScore();
                            if (null != formula && !"".equals(formula)) {
                                formula = formula.trim();// 去除公式中空字符串
                                try {
                                    gradeResultVO.setScore(computeResultByFormula(analyzeFormulaProcess(formula, paramMap, gradeResultReturnVO, gradeInfoMap, gradeModelElementMap)));
                                } catch (RuntimeException e) {
                                    logger.error("评分计算失败，模型"
                                            + gradeResultReturnVO.getGradeModelInfo()
                                            .getModelName() + "中["
                                            + gradeResultVO.getGradeNo() + "-"
                                            + gradeResultVO.getGradeName() + "]指标得分公式配置有误，请检查---》" + e);
                                    throw new Exception("评分计算失败，模型"
                                            + gradeResultReturnVO.getGradeModelInfo()
                                            .getModelName() + "中["
                                            + gradeResultVO.getGradeNo() + "-"
                                            + gradeResultVO.getGradeName() + "]指标得分公式配置有误，请检查");
                                }
                            } else {
                                logger.error("指标[" + gradeNo + "-"
                                        + gradeModelElement.getElementName() + "]为在模型["
                                        + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                        + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                        + "]中要素分值公式配置有误");
                                throw new Exception("指标[" + gradeNo + "-"
                                        + gradeModelElement.getElementName() + "]为在模型["
                                        + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                        + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                        + "]中要素分值公式配置有误");
                            }
                        }
                        gradeResultVO.setState(GradeResultVO.STATE_0);
                    }
                } else {// 其它情况 如：可能存在不用指标当前值与模型指标配置要素分值进行比较的情况，即：直接通过指标得到得分值
                    /** *****其它情况******************begin:***************** */
                    if (gradeModelElementListList == null || gradeModelElementListList.size() == 0) {
                        if (gradeModelElement.getElementIgnore().equals(Constants.FLAG_ON)) {
                            // 若不存在指标要素值并且可忽略指标，则设置为"4-无法评分,可忽略"
                            gradeResultVO.setState(GradeResultVO.STATE_3);
                        } else { // 若不存在指标要素值并且不可忽略指标，则设置为"5-无法评分,不可忽略"
                            gradeResultVO.setScore("0");
                            gradeResultVO.setState(GradeResultVO.STATE_5);
                        }
                    } else {
                        GradeModelElementList gradeModelElementList = (GradeModelElementList) gradeModelElementListList.get(0);
                        // 分计算公式和定值处理
                        if (Constants.SCORE_TYPE_1.equals(gradeModelElementList.getScoreType())) { // 定值
                            gradeResultVO.setScore(String.valueOf(gradeModelElementList.getScore()));
                        } else { // 计算公式
                            // 解析公式别并计算结果
                            String formula = gradeModelElementList.getScore();
                            if (null != formula && !"".equals(formula)) {
                                formula = formula.trim();// 去除公式中空字符串
                                gradeResultVO.setScore(computeResultByFormula(analyzeFormulaProcess(formula, paramMap, gradeResultReturnVO, gradeInfoMap, gradeModelElementMap)));
                            } else {
                                logger.error("指标[" + gradeNo + "-"
                                        + gradeModelElement.getElementName() + "]为在模型["
                                        + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                        + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                        + "]中要素分值公式配置有误");
                                throw new Exception("指标[" + gradeNo + "-"
                                        + gradeModelElement.getElementName() + "]为在模型["
                                        + gradeResultReturnVO.getGradeModelInfo().getId() + "-"
                                        + gradeResultReturnVO.getGradeModelInfo().getModelName()
                                        + "]中要素分值公式配置有误");
                            }
                        }
                        gradeResultVO.setState(GradeResultVO.STATE_0);
                    }
                    /** *****其它情况******************end***************** */
                }
            }
        }
        /** ******1 - 同时保留模型指标业务值和评分***相应处理*****end***** */

        // 若该指标不为忽略评分指标，则设置Map中，参与进行后续的计算最终结果总分,若为忽略，则不参与计算总分
        if (Constants.FLAG_ON.equals(gradeModelElement.getElementIgnore())) {
            gradeResultVO.setIsIgnore(Constants.FLAG_ON);
        } else {
            gradeResultVO.setIsIgnore(Constants.FLAG_OFF);
        }
        gradeResultVO.setGradeName(gradeModelElement.getElementName());// 指标要素名称
        gradeResultVO.setUpElementNo(gradeModelElement.getUpElementNo());//上一级指标，用于一级指标汇总分数 add by jiangxiongfei 20200824
        gradeResultReturnVO.getGradeResultMap().put(gradeDataETVO.getKey(), gradeResultVO);// Key
        // 为指标元素表中配制的字段名
    }

    /***************************************************************************
     * 保存 指标公式中涉及到的数据项
     *
     * @param brcode
     *            机构编号
     * @param trlno
     *            操作员编号
     * @param gradeModelResultDtl
     *            对应结果明细对象
     * @param mapSubDataElement
     *            对应存放指标公式数据项对象Map
     */
    public void recordGradeModelSubDataelement(Long brcode, Long trlno, GradeModelResultDtl gradeModelResultDtl, Map<String, GradeModelSubDataElementVO> mapSubDataElement) throws Exception {
        List<GradeModelSubDataelement> gradeModelSubDataelementList = gradeModelSubDataelementService.list(Wrappers.<GradeModelSubDataelement>query().lambda()
                .eq(GradeModelSubDataelement::getResultDtlId, gradeModelResultDtl.getId()));

        if (mapSubDataElement != null) {
            Iterator iter = mapSubDataElement.keySet().iterator();
            while (iter.hasNext()) {
                String subGradeCode = (String) iter.next(); // 模型指标号
                GradeModelSubDataElementVO gradeModelSubDataelementBean = mapSubDataElement.get(subGradeCode);
                /** 当指标数据项对应的指标编号 与 结果明细表中的指标编号 一致时，才可保存数据项值记录***begin:* */
                if (gradeModelResultDtl.getGradeNo().equals(gradeModelSubDataelementBean.getGradeNo())) {
                    GradeModelSubDataelement gradeModelSubDataelement = new GradeModelSubDataelement();
                    boolean opFlag = false; // 控制判断结果明细表中是否存在相同指标记录，若查找到相同的指标记录，则退出循环，进行更新操作

                    /** ***************判断结果明细表记录是否已存在****begin:******************* */
                    if (gradeModelSubDataelementList != null) {
                        Iterator gradeModelSubDataelementIter = gradeModelSubDataelementList.iterator();
                        while (gradeModelSubDataelementIter.hasNext() && !opFlag) {
                            GradeModelSubDataelement gradeModelSubDataelementTemp = (GradeModelSubDataelement) gradeModelSubDataelementIter.next();
                            if (gradeModelSubDataelementTemp.getSubGradeCode().equals(gradeModelSubDataelementBean.getSubGradeCode())) {
                                try {
                                    org.apache.commons.beanutils.BeanUtils.copyProperties(gradeModelSubDataelement, gradeModelSubDataelementTemp);
                                } catch (IllegalAccessException e) {
                                    logger.error("recordGradeModelSubDataelement指标公式数据项存取错误" + e.getMessage());
                                    throw new Exception("recordGradeModelSubDataelement指标公式数据项存取错误");
                                } catch (InvocationTargetException e) {
                                    log.error("recordGradeModelSubDataelement指标公式数据项存取错误" + e.getMessage());
                                    throw new Exception("recordGradeModelSubDataelement指标公式数据项存取错误");
                                }// 对象属性复制
                                opFlag = true;
                                // gradeModelSubDataelementDAO.getHibernateTemplate().evict(gradeModelSubDataelementTemp);// 清除对象缓存
                            }
                        }
                    }
                    /** ***************判断结果明细表记录是否已存在***********end********** */

                    gradeModelSubDataelement.setSubGradeCode(gradeModelSubDataelementBean.getSubGradeCode());
                    gradeModelSubDataelement.setSubGradeName(gradeModelSubDataelementBean.getSubGradeName());
                    gradeModelSubDataelement.setSubGradeValue(gradeModelSubDataelementBean.getSubGradeValue());
                    gradeModelSubDataelement.setRemark(gradeModelSubDataelementBean.getRemark());
                    gradeModelSubDataelement.setResultDtlId(gradeModelResultDtl.getId());// 设置评分结果明细表ID
                    gradeModelSubDataelement.setLastUpdDate(new Date());
                    gradeModelSubDataelement.setLastUpdTlr(trlno == null ? 0L : trlno);
                    if (opFlag) { // true,更新操作
                        gradeModelSubDataelementService.saveOrUpdate(gradeModelSubDataelement);
                    } else {// false,新增操作
                        gradeModelSubDataelementService.save(gradeModelSubDataelement);
                    }
                }
                /** 当指标数据项对应的指标编号 与 结果明细表中的指标编号 一致时，才可保存数据项值记录***end* */
            }
        }
    }

    /**
     * 通过给定公式计算结果
     *
     * @param formula 公式字符串
     * @return
     * @throws Exception
     */
    private String computeResultByFormula(String formula) throws Exception {
        String returnScoreValue = "0";// 分值默认0
        returnScoreValue = GradeModelCalcService.getInstance().returnResult(formula);

        return returnScoreValue;
    }

    /**
     * 解析指标公式,并获得最后结果
     * -- for 授信管理 > 授信申请 > 授信方案建立 债项评级 第一屏
     *
     * @param formula              指标公式
     * @param paramMap             当前指标公式中的代码数据项,包括指标当前值、指标权重分、引用其它指标值、引用其它指标得分值等；
     *                             对引用其它指标业务当前值，代码必须用grade_model_elements表中[grandNo]表示格式
     *                             对引用其它指标得分值，代码必须用grade_model_elements表中{grandNo}表示格式
     * @param gradeResultReturnVO  已计算的各指标结果
     * @param gradeInfoMap         页面或批量或其它途径传入的Map值
     *                             (如：gradeDataETBean.setCode(gradeno);gradeDataETBean.setKey(gradeFieldName);
     *                             gradeDataETBean.setValue(value); gradeInfoMap.put(gradeno,
     *                             gradeDataETBean); )
     * @param gradeModelElementMap 该模型下对应的绑定指标关系 *
     * @return 指标结果
     * @throws Exception
     */
    public String analyzeFormulaProcess(String formula, Map paramMap, GradeResultReturnVO gradeResultReturnVO, Map gradeInfoMap, Map gradeModelElementMap) throws Exception {
        int m = formula.lastIndexOf("{");
        String gradeCodeTmp = "";// 临时字符串变量
        String gradeNo = "";// 指标编号
        String gradeValue = "0";// 指标当前值

        // GradeModelElementsDAO gradeModelElementsDAO =
        // DAOUtils.getGradeModelElementsDAO();

        /** *支持对公式中"{}"的解析，表示的某指标的最终得分,其中的符号代码需要被得分结果代替**begin:** */
        if (m >= 0) { // 公式中存在其他指标项定义
            while (m >= 0) {
                int n = formula.lastIndexOf("}");
                gradeCodeTmp = formula.substring(m, n + 1); // 如：{1}
                gradeNo = formula.substring(m + 1, n); // 如：1
                // 对应grade_model_elements表中的grandNo
                GradeResultReturnVO newradeResultReturnBean = new GradeResultReturnVO();
                newradeResultReturnBean
                        .setGradeModelInfo(gradeResultReturnVO.getGradeModelInfo());
                newradeResultReturnBean.setModelCode(gradeResultReturnVO.getModelCode());
                /** *获取单个指定指标对应的模型配置中指标对应的分值***不考虑权重及特殊要求的得分值*****begin:**** */
                this.getGradeSingleElementResult(newradeResultReturnBean, gradeInfoMap,
                        gradeModelElementMap, gradeNo);
                /** *获取单个指定指标对应的模型配置中指标对应的分值***不考虑权重及特殊要求的得分值*****end**** */

                /** *计算指定指标要素得分，已考虑到权重及特殊要求得分值***begin:*** */
                this.getGradeScore(newradeResultReturnBean, true);
                /** *计算指定指标要素得分，已考虑到权重及特殊要求得分值***end*** */
                formula = formula.replace(gradeCodeTmp, newradeResultReturnBean.getScore().toString());
                m = formula.lastIndexOf("{");
            }
        }
        /** *支持对公式中"{}"的解析，表示的某指标的最终得分,其中的符号代码需要被得分结果代替**end** */

        /** *支持对公式中"[]"的解析，表示的某指标的业务当前值,其中的符号代码需要被业务当前值代替**begin:** */
        int i = formula.lastIndexOf("[");
        if (i >= 0) { // 公式中存在其他指标项定义
            while (i >= 0) {
                int j = formula.lastIndexOf("]");
                gradeCodeTmp = formula.substring(i, j + 1); // 如：[1]
                gradeNo = formula.substring(i + 1, j); // 如：1
                // 对应grade_model_elements表中的grandNo
                GradeDataETVO gradeDataETVO = (GradeDataETVO) gradeInfoMap.get(gradeNo);

                if (gradeDataETVO != null) {

                    gradeValue = ("".equals(gradeDataETVO.getValue())
                            || null == gradeDataETVO.getValue() ? "0" : gradeDataETVO
                            .getValue());

                }

                /*
                 * 原代码 GradeModelElements gradeModelElements =
                 * gradeModelElementsDAO.query(Integer.parseInt(grandNo));
                 * GradeResultBean gradeResultBean =
                 * (GradeResultBean)gradeResultReturnBean.getGradeResultMap().get(gradeModelElements.getGradeFieldNm());
                 * gradeValue = gradeResultBean.getValue(); //获取指标当前值
                 */
                formula = formula.replace(gradeCodeTmp, gradeValue);
                i = formula.lastIndexOf("[");
            }
        }
        /** *支持对公式中"[]"的解析，表示的某指标的业务当前值,其中的符号代码需要被业务当前值代替**end* */

        // 替换Map中的公式中 非指标项的 代码标识，最终得出相应运算表达式 begin:
        Iterator iter = paramMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            formula = formula.replace(key, String.valueOf(paramMap.get(key)));
        }
        // 替换Map中的公式中 非指标项的 代码标识，最终得出相应运算表达式 end

        return formula;
    }

    /**
     * 对于区间定值型，才调用到此方法 通过区间值判断符合的指标要素分值
     *
     * @param gradeDataETVO     外界（可能页面，批量）所传信息
     * @param modelElementsList 指标要素分值列表
     * @return GradeModelElementsList 对象
     * @author lizh
     * @date 2010-11-04
     */
    private GradeModelElementList getGradeModelElementListByLimit(GradeDataETVO gradeDataETVO, List modelElementsList) throws Exception {
        if (CollectionUtils.isNotEmpty(modelElementsList)) {
            for (int i = 0; i < modelElementsList.size(); i++) {
                GradeModelElementList gradeModelElementsList = (GradeModelElementList) modelElementsList.get(i);
                BigDecimal lowLimit = gradeModelElementsList.getLowLimit(); // 下限值
                BigDecimal highLimit = gradeModelElementsList.getHighLimit();// 上限值
                Boolean islowLimit = gradeModelElementsList.getIsLowLimit();// 是否包含下限值标志
                Boolean isHighLimit = gradeModelElementsList.getIsHighLimit();// 是否包含上限值标志
                if (null == lowLimit) {// 说明不存在下限值控制,必存在上限值,需要通过isHighLimit
                    // 值判断是否含有上限值
                    if (highLimit == null) {
                        throw new Exception("评分计算失败，模型指标分值配置有误，若为区间定值，则上下限值不能同时为空!");
                    }
                    if ((isHighLimit)) {// 包含上限值
                        if (highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != -1) {// 不等于
                            // -1，则说明上限值大于等于当前值;即：highLimit>=当前值
                            return gradeModelElementsList;
                        }
                    } else {
                        if (highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == 1) {// 等于1，则说明上限值大于当前值;即：highLimit>
                            // 当前值
                            return gradeModelElementsList;
                        }
                    }
                } else {// 存在下限值，则有可能不存在上限值,需要highLimit再次判断
                    if (lowLimit == null) {
                        throw new Exception("评分计算失败，模型指标分值配置有误，若为区间定值，则上下限值不能同时为空!");
                    }
                    if (highLimit == null) {// 说明不存在上限值
                        if ((islowLimit)) {// 包含下限值；即：lowLimit<=
                            // 当前值
                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != 1) {// 下限值不大于当前值
                                return gradeModelElementsList;
                            }
                        } else {
                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == -1) {// 下限值小于当前值;即：lowLimit<
                                // 当前值
                                return gradeModelElementsList;
                            }
                        }
                    } else {// 否则既存在下限值，也存在上限值，需要通过islowLimit和isHighLimit
                        // 值判断是否含有上下限值
                        if ((islowLimit)
                                && (isHighLimit)) {// 包含上下限值
                            // 即：lowLimit<=
                            // 当前值
                            // <=highLimit
                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != 1
                                    && highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != -1) {
                                return gradeModelElementsList;
                            }
                        } else if ((islowLimit)
                                && !(isHighLimit)) {// 包含下限值，不含上限值;即：lowLimit<=
                            // 当前值
                            // <highLimit

                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != 1
                                    && highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == 1) {
                                return gradeModelElementsList;
                            }
                        } else if (!(islowLimit)
                                && !(isHighLimit)) {// 不含上下限值;即：lowLimit<
                            // 当前值
                            // <
                            // highLimit
                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == -1
                                    && highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == 1) {
                                return gradeModelElementsList;
                            }
                        } else {// 不含下限值但包含上限值;即：lowLimit< 当前值 <= highLimit
                            if (lowLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) == -1
                                    && highLimit.compareTo(new BigDecimal(gradeDataETVO.getValue())) != -1) {
                                return gradeModelElementsList;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * @param score
     * @return
     * @throws Exception
     * @Title getGradeByScore
     * @Description -- for 授信管理 > 授信申请 > 授信方案建立 第三屏 查看客户信用评级个体户
     * -- for 授信管理 > 授信申请 > 授信方案建立 第三屏 查看客户信用评级对公客户
     */
    public String getGradeByScore(BigDecimal score) throws Exception {
        String grade = "01"; // 默认AAA
        List<GradeScoreRela> relaList = gradeScoreRelaService.list();
        if (CollectionUtils.isNotEmpty(relaList)) {
            for (int i = 0; i < relaList.size(); i++) {
                GradeScoreRela rela = (GradeScoreRela) relaList.get(i);
                BigDecimal lowLimit = rela.getLowLimit(); // 下限值
                BigDecimal highLimit = rela.getHighLimit();// 上限值
                String islowLimit = rela.getLowLimitFlg();// 是否包含下限值标志
                String isHighLimit = rela.getHighLimitFlg();// 是否包含上限值标志
                String gradeType = rela.getGradeType();// 是否包含上限值标志
                if (null != gradeType && gradeType.equals("1")) {
                    if (rela.getGrade() == null && !"".equals(rela.getGrade())) {
                        throw new Exception("模型得分与对应关系配置错误，请查找相应模型对应关系!");
                    }
                    if (null == lowLimit) {// 说明不存在下限值控制,必存在上限值,需要通过isHighLimit
                        // 值判断是否含有上限值
                        if (highLimit == null) {
                            throw new Exception("评分计算失败，模型指标分值配置有误，若为区间定值，则上下限值不能同时为空!");
                        }
                        if (Constants.FLAG_ON.equals(isHighLimit)) {// 包含上限值
                            if (highLimit.compareTo(score) != -1) {// 不等于
                                // -1，则说明上限值大于等于当前值;即：highLimit>=当前值
                                return rela.getGrade();
                            }
                        } else {
                            if (highLimit.compareTo(score) == 1) {// 等于1，则说明上限值大于当前值;即：highLimit>
                                // 当前值
                                return rela.getGrade();
                            }
                        }
                    } else {// 存在下限值，则有可能不存在上限值,需要highLimit再次判断
                        if (lowLimit == null) {
                            throw new Exception("评分计算失败，模型指标分值配置有误，若为区间定值，则上下限值不能同时为空!");
                        }
                        if (highLimit == null) {// 说明不存在上限值
                            if (Constants.FLAG_ON.equals(islowLimit)) {// 包含下限值；即：lowLimit<=
                                // 当前值
                                if (lowLimit.compareTo(score) != 1) {// 下限值不大于当前值
                                    return rela.getGrade();
                                }
                            } else {
                                if (lowLimit.compareTo(score) == -1) {// 下限值小于当前值;即：lowLimit<
                                    // 当前值
                                    return rela.getGrade();
                                }
                            }
                        } else {// 否则既存在下限值，也存在上限值，需要通过islowLimit和isHighLimit
                            // 值判断是否含有上下限值
                            if (Constants.FLAG_ON.equals(islowLimit) && Constants.FLAG_ON.equals(isHighLimit)) {// 包含上下限值
                                // 即：lowLimit<= 当前值 <=highLimit
                                if (lowLimit.compareTo(score) != 1 && highLimit.compareTo(score) != -1) {
                                    return rela.getGrade();
                                }
                            } else if (Constants.FLAG_ON.equals(islowLimit) && Constants.FLAG_OFF.equals(isHighLimit)) {// 包含下限值，不含上限值;即：lowLimit<=
                                // 当前值 <highLimit

                                if (lowLimit.compareTo(score) != 1 && highLimit.compareTo(score) == 1) {
                                    return rela.getGrade();
                                }
                            } else if (Constants.FLAG_OFF.equals(islowLimit) && Constants.FLAG_OFF.equals(isHighLimit)) {// 不含上下限值;即：lowLimit<
                                // 当前值 < highLimit
                                if (lowLimit.compareTo(score) == -1 && highLimit.compareTo(score) == 1) {
                                    return rela.getGrade();
                                }
                            } else {// 不含下限值但包含上限值;即：lowLimit< 当前值 <= highLimit
                                if (lowLimit.compareTo(score) == -1 && highLimit.compareTo(score) != -1) {
                                    return rela.getGrade();
                                }
                            }
                        }
                    }
                }
            }
        }
        return grade;
    }

    /**
     * 根据客户和期次获取资产负债率
     * @param custcd
     * @param term
     * @return
     * @throws Exception
     */
/*    private BigDecimal getDsRatio(String custcd, String term) throws Exception {
        BigDecimal bsRatio = BigDecimal.ZERO;
        HQLDAO hqldao = IfincarDAOUtils.getHQLDAO();
        String hql = "select analyseData from RptAnalyseData where (id.recordNo='324" + custcd + "0103' and id.rptNo='" + term + "' and id.analyseDataCode='0804') "
                + "or (id.recordNo='324" + custcd + "0104' and id.rptNo='" + term + "' and id.analyseDataCode='0843')";
        Iterator it = hqldao.queryByQL(hql);
        if (it.hasNext()) {
            bsRatio = (BigDecimal) it.next();
        }
        return bsRatio;
    }*/

    /**
     * 根据客户和期次获取净利润
     * @param custcd
     * @param term
     * @return
     * @throws Exception
     */
/*    private BigDecimal getNetProfit(String custcd, String term) throws Exception {
        BigDecimal netProfit = BigDecimal.ZERO;
        HQLDAO hqldao = IfincarDAOUtils.getHQLDAO();
        String hql = "select analyseData from RptAnalyseData where (id.recordNo='324" + custcd + "0103' and id.rptNo='" + term + "' and id.analyseDataCode='0861') "
                + "or (id.recordNo='324" + custcd + "0104' and id.rptNo='" + term + "' and id.analyseDataCode='0862')";
        Iterator it = hqldao.queryByQL(hql);
        if (it.hasNext()) {
            netProfit = (BigDecimal) it.next();
        }
        return netProfit;
    }*/

    /**
     * 取客户最近一期报表期次
     * @param custcd
     * @return
     * @throws Exception
     */
/*
    private String getLastTerm(String custcd) throws Exception {
        HQLDAO hqldao = IfincarDAOUtils.getHQLDAO();
        String lastTerm = RcmsSystemConstant.CLR_CLASS_NORMAL;
        String hql = "select nvl(max(po.id.rptNo),0) from RptDataBaseInfo po where po.id.custcd='" + custcd + "'";
        List list = hqldao.queryByQL2List(hql);
        if (list != null && list.size() > 0) {
            lastTerm = (String) list.get(0);
        }
        return lastTerm;
    }
*/


    /**
     * 取该客户下最差的五级分类
     *
     * @param custcd
     * @return
     * @throws Exception
     */
 /*   private String getFiveClass(String custcd) throws Exception {
        HQLDAO hqldao = IfincarDAOUtils.getHQLDAO();
        String fiveClass = RcmsSystemConstant.CLR_CLASS_NORMAL;
        String hql = "select nvl(max(po.clrClass),0) from Loancino po where po.custcd='" + custcd + "'";
        List list = hqldao.queryByQL2List(hql);
        if (list != null && list.size() > 0) {
            fiveClass = (String) list.get(0);
        }
        return fiveClass;
    }*/
}
